package com.nova.edc.service.system.impl;

import com.nova.edc.dao.system.AreaPointDao;
import com.nova.edc.dao.system.CustomerAreaDao;
import com.nova.edc.dao.system.CustomerInfoDao;
import com.nova.edc.model.energy.Gather;
import com.nova.edc.model.system.*;
import com.nova.edc.model.util.ExcelArea;
import com.nova.edc.service.energy.GatherService;
import com.nova.edc.service.system.AreaPointService;
import com.nova.edc.service.system.CustomerAreaService;
import com.nova.edc.service.system.CustomerInfoService;
import com.nova.frame.dao.buzz.query.Order;
import com.nova.frame.dao.buzz.query.Query;
import com.nova.frame.dao.criterion.MatchMode;
import com.nova.frame.dao.criterion.Restrictions;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.frame.transaction.annotation.Transactional;
import com.nova.frame.utils.JdbcUtils;
import com.nova.module.filter.query.Filter;
import com.nova.module.sql.SqlBuffer;
import com.nova.module.util.StringUtils;
import com.seio.edc.common.Constants;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * @param
 * @author <a href="mailto:huzhanjun@novacloud.com">huzj</a>
 * @version : 1.0
 * @date 2015-12-21 14:33
 */
public class CustomerAreaServiceImpl implements CustomerAreaService {

    @Autowired
    private CustomerAreaDao customerAreaDao;

    @Autowired
    private CustomerInfoService novaCustomerInfoService;

    @Autowired
    private CustomerInfoDao customerInfoDao;

    @Autowired
    private AreaPointDao areaPointDao;

    @Autowired
    private GatherService novaGatherService;

    //添加
    @Override
    public CustomerArea insert(CustomerArea customerArea) {
        CustomerArea customerArea1 = checkInsert(customerArea);
        if (customerArea1 != null) {
            return customerArea1;
        } else {
            return customerAreaDao.insert(customerArea);
        }
    }

    @Override
    public CustomerArea checkInsert(CustomerArea customerArea) {
        List<CustomerArea> customerAreaList = customerAreaDao.query().add(Restrictions.eq("AreaName", customerArea.getAreaname()))
                .add(Restrictions.eq("CustomerInfoId", customerArea.getCustomerinfoid())).list();
        if (customerAreaList.size() > 0) {
            return customerAreaList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void insertByExcel(List<ExcelArea> excelAreaList) {
        for (ExcelArea excelArea : excelAreaList) {
            CustomerInfo customerInfo = customerInfoDao.query().add(Restrictions.eq("CompanyCode", excelArea.getCompanycode())).get();
            CustomerArea customerArea = new CustomerArea();
            customerArea.setCustomerinfoid(customerInfo.getId());
            customerArea.setAreaname(excelArea.getAreaname());
            if (StringUtils.isNullOrEmpty(excelArea.getAreaname()) || "无".equals(excelArea.getAreaname())) {
                customerArea.setAreaname(ModelConstant.DEVICE_OTHER);
            }
            excelArea.setCustomerinfoid(customerInfo.getId());
            excelArea.setAreaid(insert(customerArea).getId());
        }
    }

    //byId
    @Override
    public PageList<CustomerArea> findPageCustomerArea(CustomerArea customerArea,
                                                       Page page, String sidx, String sord) {
        if (StringUtils.isNotNullOrEmpty(customerArea.getAreaname())) {
            customerArea.setAreaname(customerArea.getAreaname().trim());
        }
        Query<CustomerArea> query = customerAreaDao.query();
        query.addOrder(Order.custom(sord, sidx));
        Filter.addFilterCondition(query, customerArea);
        return query.pageList(page);
    }

    @Override
    public PageList<CustomerArea> findPageCustomerAreaDetail(CustomerArea customerArea, Page page, String sidx, String sord) {
        PageList<CustomerArea> pageList = new PageList<CustomerArea>();
        SqlBuffer sqlBuffer = new SqlBuffer("SELECT " +
                " t_customer_area.ID id, " +
                " AreaCode areacode, " +
                " AreaName areaname, " +
                " count(t_area_point.ID) pointnum, " +
                " sum(Power_1) trapower, " +
                " sum(Power_2) ledpower, " +
                " sum(RealPower) realpower " +
                " FROM t_customer_area " +
                " LEFT JOIN t_area_point " +
                " ON t_customer_area.ID = t_area_point.AreaId " +
                " WHERE t_customer_area.CustomerInfoId = ? " +
                " AND AreaName <> ? AND AreaName LIKE ? " +
                " GROUP BY AreaCode, AreaName " +
                " ORDER BY sum(RealPower) DESC", false);
        int rowCount = JdbcUtils.count(sqlBuffer.getCountSql(), customerArea.getCustomerinfoid(), ModelConstant.AREA_ONLINE
                , customerArea.getAreaname() == null ? "%%" : "%" + customerArea.getAreaname().trim() + "%").intValue();
        List<CustomerArea> list = JdbcUtils.query_limit(
                CustomerArea.class, sqlBuffer.getSelectSql(), page, customerArea.getCustomerinfoid(), ModelConstant.AREA_ONLINE
                , customerArea.getAreaname() == null ? "%%" : "%" + customerArea.getAreaname().trim() + "%");
        page.make(rowCount);
        pageList.setDatas(list);
        pageList.setPage(page);
        return pageList;
    }

    @Override
    public CustomerArea findById(int id) {
        return customerAreaDao.getById(id);
    }

    @Override
    public int update(CustomerArea customerArea) {
        return customerAreaDao.updateNotNull(customerArea);
    }

    @Override
    @Transactional
    public int delete(int id) {
        areaPointDao.delete(Restrictions.eq("AreaId", id));
        return customerAreaDao.deleteById(id);
    }

    @Override
    public int deleteByCustomerArea(CustomerArea customerArea) {
        return this.customerAreaDao.deleteByExample(customerArea);
    }

    @Override
    public List<CustomerArea> findCustomerArea(CustomerArea customerArea) {
        return this.customerAreaDao.findByExample(customerArea);
    }


    @Override
    public void wrapEnergy(CustomerArea customerArea, String startDate, String endDate) {
        String sql = "SELECT sum(energy) energy " +
                "FROM (SELECT sum(t_summary.ActiveState*t_area_point.power_2/60000) energy " +
                "      FROM t_summary " +
                "        LEFT JOIN t_area_point " +
                "          ON t_summary.PointID = t_area_point.ID " +
                "      WHERE t_summary.CompanyCode = ? " +
                "            AND t_summary.AreaID = ? " +
                "            AND SummaryDate >= ? " +
                "            AND SummaryDate <= ? " +
                "      GROUP BY t_summary.PointID) detail";
        CustomerInfo customerInfo = novaCustomerInfoService.getById(customerArea.getCustomerinfoid());
        Map<String, Object> energy = JdbcUtils.getMap(sql, customerInfo.getCompanycode(), customerArea.getId(), startDate, endDate);
        Number result = (Number) energy.get("energy");
        customerArea.setEnergy(result == null ? 0 : result.doubleValue());
    }

    @Override
    public void wrapEnergy(List<CustomerArea> customerAreas, String startDate, String endDate) {
        for (CustomerArea customerArea : customerAreas) {
            wrapEnergy(customerArea, startDate, endDate);
        }
    }

    @Override
    public void wrapGather(List<CustomerArea> customerAreas, String startDate, String endDate) {
        for (CustomerArea customerArea : customerAreas) {
            wrapGather(customerArea, startDate, endDate);
        }
    }

    @Override
    public void wrapGather(CustomerArea customerArea, String startDate, String endDate) {
        String sql = "SELECT " +
                "  AreaId, " +
                "  sum(ActiveTime * t_gather_summary.RealPower / 60000) energy " +
                "FROM t_gather_summary " +
                "WHERE AreaId = ? AND SummaryDate >= ? AND SummaryDate <= ? " +
                "GROUP BY AreaId ";
        Map<String, Object> energy = JdbcUtils.getMap(sql, customerArea.getId(), startDate, endDate);
        if (energy != null) {
            Number result = (Number) energy.get("energy");
            customerArea.setEnergy(result == null ? 0 : result.doubleValue());
        } else {
            customerArea.setEnergy(0.0);
        }
    }

    @Override
    public CustomerArea getByarea(String areaName, Integer customerinfoId) {
        return customerAreaDao.query().add(Restrictions.like("AreaName", areaName, MatchMode.ANYWHERE)).add(Restrictions.eq("CustomerInfoId", customerinfoId)).get();

    }

    @Override
    public boolean existCustomerArea(CustomerArea customerArea) {
        Query<CustomerArea> query = customerAreaDao.query()
                .add(Restrictions.eq("t_customer_area.CustomerInfoId", customerArea.getCustomerinfoid()))
                .add(Restrictions.eq("t_customer_area.AreaName", customerArea.getAreaname()));
        if (customerArea.getId() != null && customerArea.getId() != 0) {
            query.add(Restrictions.ne("t_customer_area.ID", customerArea.getId()));
        }
        int size = query.list().size();
        return size == 0;
    }

    @Override
    public List<CustomerArea> findByCustomereInfoIdAPI(Integer id) {
        Query<CustomerArea> query = customerAreaDao.query()
                .add(Restrictions.eq("t_customer_area.CustomerInfoId", id))
                .add(Restrictions.ne("t_customer_area.AreaName", ModelConstant.DEVICE_OTHER))
                .add(Restrictions.ne("t_customer_area.AreaName",ModelConstant.AREA_ONLINE))
                .addOrder(Order.asc("t_customer_area.ID"));
        return query.list();
    }
}
